import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Result } from "src/common/Result";
import { CollectionUtils } from "src/common/utils/CollectionUtils";
import { GoodsDto } from "src/dto/GoodsDto";
import { StockDto } from "src/dto/StockDto";
import { Goods } from "src/entity/Goods";
import { Stock } from "src/entity/Stock";
import { Repository } from "typeorm";

@Injectable()
export class StockService {
    
    @InjectRepository(Stock)
    private stockRepository: Repository<Stock>;

    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>;

    /**
     * 库存列表查询
     * @param query 
     * @returns 
     */
    async selectUnitStock(query: StockDto) {
        let one = await this.goodsRepository.findOneBy({goodsCode: query.goodsCode});

        let data = this.stockRepository.query(`
        select
            s.id,
            u.unit_id as unitId,
            u.unit,
            (select goods_code from goods where id = ${one.id}) as goodsCode,
            IFNULL(s.count,0) as count ,
            g.goods_name as goodsName
        from unit as u
        left join stock as s on u.unit_id = s.unit_id and s.goods_id = ${one.id}
        left join goods as g on s.goods_id = g.id
        `);
        return data;
    }


    /**
     * 进货
     * @param dto 
     */
    async updateStock(dto: GoodsDto) {
        let {stockList} = dto;
        let one = await this.goodsRepository.findOne({
            where: {
                goodsCode: dto.goodsCode
            },
            relations: [
                "stockList"
            ]
        });
        if (!one) {
            return Result.failed("数据异常!");
        }
        if (CollectionUtils.isEmpty(one.stockList)) {
            stockList.forEach(item => {
                let stock = new Stock();
                stock.goodsId = one.id;
                stock.unitId = item.unitId;
                stock.count = item.count;

                one.stockList = [...one.stockList, stock];
            })

        }
        one.stockList?.forEach(item => {
            if (CollectionUtils.isNotEmpty(stockList)) {
                if (dto.inOrOut == "IN") {
                    let stock = stockList.find(o => o.unitId == item.unitId);
                    item.count += stock?.count || 0;
                } else if (dto.inOrOut == "OUT") {
                    let stock = stockList.find(o => o.unitId == item.unitId);
                    item.count = (item.count - stock?.count) < 0 ? 0: (item.count - stock?.count)
                }
            }
        })
        // await this.stockRepository.manager.transaction(async transaction => {
        //
        //
        // })
        await this.stockRepository.save(one.stockList);
        return Result.success();
    }
}